package com.hxgis.oc.util;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Slf4j
public class CommandInvoker {
    public static boolean invoke(String application, String[] params) throws IOException, InterruptedException {
        List<String> list = new ArrayList<>();
        list.add(application);
        list.addAll(Arrays.asList(params));
        return invoke(list.toArray(new String[0]));
    }

    public static boolean invoke(String[] command) throws IOException, InterruptedException {
        Process process = Runtime.getRuntime().exec(command);
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
        BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
        String s;
        while ((s = stdInput.readLine()) != null) {
            log.debug(s);
        }
        while ((s = stdError.readLine()) != null) {
            log.error(s);
        }
        int exitStatus = process.waitFor();
        if (exitStatus != 0) {
            log.error("exec cmd exitStatus {}", exitStatus);
        }
        return exitStatus == 0;
    }
}
